<template>
  <div>
    <form novalidate class="md-layout" @submit.prevent="validateTask">
      <md-card class="md-layout-item md-size-50 md-small-size-100">
        <md-card-header>
          <div class="md-title">添加任务</div>
        </md-card-header>

        <md-card-content>
          <div class="md-layout md-gutter">
            <div class="md-layout-item md-small-size-100">
              <md-field :class="getValidationClass('taskContent')">
                <label for="task-content">任务内容</label>
                <md-input name="task-content" id="task-content"  autocomplete="given-name" v-model="form.taskContent"
                          :disabled="sending"/>
                <span class="md-error" v-if="!$v.form.taskContent.required">请输入任务内容</span>
              </md-field>
            </div>
          </div>

          <!-- vue-materail 实现的开始时间，结束时间 -->
         <!-- <div class="md-layout md-gutter">
            <div class="md-layout-item md-small-size-100">
              <md-field :class="getValidationClass('startTime')">
                <label for="start-time">开始时间</label>
                <md-datepicker name="start-time" type="time" id="start-time" v-model="form.startTime" md-immediately/>
                <span class="md-error" v-if="!$v.form.startTime.required">请输入任务开始时间</span>
              </md-field>
            </div>

            <div class="md-layout-item md-small-size-100">
              <md-field :class="getValidationClass('endTime')">
                <label for="end-time">结束时间</label>
                 <md-datepicker v-model="form.endTime" name="end-time" id="end-time" md-immediately/>
               &lt;!&ndash; <mu-date-input id="end-time" v-model="form.endTime"  type="dateTime" ></mu-date-input>&ndash;&gt;
                <span class="md-error" v-if="!$v.form.endTime.required">请输入任务结束时间</span>
              </md-field>
            </div>
          </div>-->


          <!-- element-ui-->
          <div class="md-layout md-gutter">
            <div class="md-layout-item md-small-size-100">
              <md-field :class="getValidationClass('startTime')">
                <label for="start-time">开始时间</label>
                <!-- 日期选择 -->
                <el-date-picker
                  id="start-time"
                  v-model="form.startTime"
                  type="datetime"
                  placeholder="开始时间"
                  align="center">
                </el-date-picker>
                <span class="md-error" v-if="!$v.form.startTime.required">请输入任务开始时间</span>
              </md-field>
            </div>

            <div class="md-layout-item md-small-size-100">
              <md-field :class="getValidationClass('endTime')">
                <label for="end-time">结束时间</label>
                <!-- 日期选择 -->
                <el-date-picker
                  id="end-time"
                  v-model="form.endTime"
                  type="datetime"
                  placeholder="结束时间"
                  align="center">
                </el-date-picker>
                <span class="md-error" v-if="!$v.form.endTime.required">请输入任务结束时间</span>
              </md-field>
            </div>
          </div>

          <div class="md-layout md-gutter">
            <div class="md-layout-item md-small-size-100">
              <md-field :class="getValidationClass('importance')">
                <label for="importance">重要性</label>
                <md-input name="importance" type="number" id="importance" v-model.number="form.importance" md-dense
                          :disabled="sending">
                </md-input>
                <span class="md-error" v-if="!$v.form.importance.required">请输入任务重要性</span>
              </md-field>
            </div>
          </div>


        </md-card-content>

        <md-progress-bar md-mode="indeterminate" v-if="sending"/>

        <md-card-actions>
          <md-button type="submit" class="md-primary" :disabled="sending">确定</md-button>
        </md-card-actions>
      </md-card>

      <md-snackbar :md-active.sync="msg.showMsg" :md-duration="msg.duration" :md-position="msg.position">{{ msg.content }} </md-snackbar>
    </form>
  </div>
</template>

<script>
  import {validationMixin} from 'vuelidate'
  import * as taskService from '@/util/service/TaskService'
  import {
    required,
    minLength,
    maxLength
  } from 'vuelidate/lib/validators'
  import {Task} from '@/util/entity/Task'
  import axios from 'axios/index'

  export default {
    name: 'task',
    mixins: [validationMixin],
    data: () => ({
      form: {
        taskContent: null,
        startTime: null,
        endTime: null,
        importance: 60
      },
      taskSaved: false,
      msg: {/* 用于配置msg */
        showMsg: false,
        content: null,
        duration: 3000,
        position: 'center'
      },
      sending: false // 是否可以输入
    }),
    /* watch: {
      '$route' (to, from) {
        // 对路由变化作出响应...
        // 为tasks赋值
        // todo 在这里判断是添加任务，还是更新任务
        if (this.$route.params.id !== null && this.$route.params.id !== undefined) {
          // todo 说明是更新任务，查询
          taskService.queryTaskById(this.$route.params.id).then((response) => {
            this.form.taskContent = response.content
            this.form.startTime = response.startTime
            this.form.endTime = response.endTime
            this.form.importance = response.importance
          }).catch(() => {
            this.message({content: '获取任务失败', position: 'center', showMsg: true})
          })
        } else {
        }
      }
    }, */
    validations: {
      form: {
        taskContent: {
          required,
          minLength: minLength(3),
          maxLength: maxLength(255)
        },
        startTime: {
          required
        },
        endTime: {
          required
        },
        importance: {
          required
        }
      }
    },
    methods: {
      getValidationClass (fieldName) {
        const field = this.$v.form[fieldName]

        if (field) {
          return {
            'md-invalid': field.$invalid && field.$dirty
          }
        }
      },
      clearForm () {
        this.$v.$reset()
        this.form.taskContent = null
        this.form.startTime = null
        this.form.endTime = null
        this.form.importance = 60
      },
      saveTask () {
        this.sending = true
        /* 其实，应该是先存在本地，在检测网络可不可用 */
        let task = new Task()
        task.content = this.form.taskContent
        // 这里需要给userId赋值
        task.userId = localStorage.getItem('userId')
        //  startTime，endTime要精确到分
        task.startTime = this.form.startTime.format(this.GLOBAL.formatDate1)
        task.endTime = this.form.endTime.format(this.GLOBAL.formatDate1)
        task.date = this.form.startTime.format(this.GLOBAL.formatDate2)
        task.id = this.$route.params.id
        task.importanceValue = this.form.importance
        // 执行存储
        taskService.saveTask(task).then((response) => {
          this.message({content: '保存任务成功', position: 'center', showMsg: true})
          this.clearForm()
          //  查询任务，将本地数据同步到后台
          taskService.queryTaskById(task.id).then((response) => {
            let token = JSON.parse(localStorage.getItem('token'))
            axios({
              data: response,
              method: 'post',
              url: this.GLOBAL.prefix + '/saveTask',
              headers: {
                Authorization: token.token_type + ' ' + token.access_token
              }
            }).catch((error) => {
              throw error
            })
          })
        }).catch((error) => {
          console.log(error)
          this.message({content: '保存任务失败', position: 'center', showMsg: true})
        })
        // Instead of this timeout, here you can call your API
        window.setTimeout(() => {
          this.taskSaved = true
          this.sending = false
          this.clearForm()
        }, 1500)
      },
      validateTask () {
        this.$v.$touch()

        if (!this.$v.$invalid) {
          this.saveTask()
        }
      },
      /**
       * 用于配置msg,option具体配置减data部分的msg
       * @param option
       */
      message (option) {
        this.msg = option
      }
    },
    mounted () {
      //  在这里判断是添加任务，还是更新任务
      if (this.$route.params.id !== null && this.$route.params.id !== undefined) {
        //  说明是更新任务，查询
        taskService.queryTaskById(this.$route.params.id).then((response) => {
          this.form.taskContent = response.content
          this.form.startTime = new Date(response.startTime)
          this.form.endTime = new Date(response.endTime)
          this.form.importance = response.importanceValue
        }).catch(() => {
          this.message({content: '获取任务失败', position: 'center', showMsg: true})
        })
      } else {
      }
    }
  }
</script>


<style lang="scss" scoped>
  .md-progress-bar {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
  }
  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%;
  }
</style>
